package com.bdqn.springbootstudy.controller;

import com.bdqn.springbootstudy.pojo.EbookEntry;
import com.bdqn.springbootstudy.service.EbookEntryService;
import com.bdqn.springbootstudy.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ecBook")
public class EController {
    @Resource
    private EbookEntryService ebookEntryService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/getAll")
    public String getAll(){
        System.out.println("从redis缓存查");
        String getAll= (String) redisUtil.get("all");
        if(getAll==null){
            System.out.println("从数据库查");
            getAll=ebookEntryService.getAllBook().toString();
            System.out.println(getAll);
            redisUtil.set("all",getAll);
        }
        return getAll;
    }
    @RequestMapping("/add")
    public Object add(){
        EbookEntry ebookEntry = new EbookEntry();
        ebookEntry.setCategoryId(3);
        ebookEntry.setTitle("sun");
        ebookEntry.setSummary("zz");
        ebookEntry.setUploaduser("wagn");
        ebookEntry.setCreatedate(new Date());
        ebookEntryService.add(ebookEntry);
        String  all = (String) redisUtil.get("all");
        String substring = all.substring(0, all.lastIndexOf("}")+1)+","+ebookEntry+"]";
        redisUtil.set("all",substring);
        return ebookEntry;
    }
}
